package com.upupwe.raspberry.app.update;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.blankj.utilcode.util.NetworkUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jess.arms.utils.ArmsUtils;
import com.upupwe.raspberry.app.model.DialogModel;
import com.upupwe.raspberry.app.utils.DialogUtils;
import com.upupwe.raspberry.app.utils.RxBus;
import com.upupwe.raspberry.mvp.model.entity.Version;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

import com.upupwe.raspberry.BuildConfig;
import com.upupwe.raspberry.mvp.ui.activity.MainActivity;

import io.reactivex.Observer;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class UpdateManager {


    public static void downLoadApk(UpdateApkService updateApkService, String apkPath, CompositeDisposable mCompositeDisposable) {

        Gson gson = new GsonBuilder().setLenient().create();
        OkHttpClient client = new OkHttpClient().newBuilder()
                .addInterceptor(chain -> {
                    Response originalResponse = chain.proceed(chain.request());
                    return originalResponse
                            .newBuilder()
                            .body(new ApkResponseBody(originalResponse))
                            .build();
                }).build();
        Retrofit retrofit = new Retrofit.Builder().baseUrl(APIManager.APP_DOMAIN).client(client)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        APIManager apiManager = retrofit.create(APIManager.class);
        apiManager.download()
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.d("test", "onSubscribe: ");
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        File file = new File(apkPath);
                        File parentFile = file.getParentFile();
                        if (!parentFile.exists()) {
                            parentFile.mkdirs();
                        }
                        try {
                            if (file.exists()) {
                                file.createNewFile();
                            }
                            OutputStream outputStream = new FileOutputStream(apkPath);
                            outputStream.write(responseBody.bytes());
                        } catch (Exception e) {
                            ArmsUtils.makeText(updateApkService, "保存文件时出错！检查是否授权！");
                            Log.d("UpdateManager", e.getMessage());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        ArmsUtils.makeText(updateApkService, "下载文件时出错，请重试。");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public static boolean checkUpdate(Context context) {
        if (!NetworkUtils.isAvailable()) {
            return false;
        }
        Retrofit retrofit = new Retrofit.Builder().baseUrl(APIManager.APP_DOMAIN)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        APIManager apiManager = retrofit.create(APIManager.class);
        apiManager.getVersion(BuildConfig.VERSION_CODE)
                .subscribe(new Observer<Version>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Version version) {
                        if (version.getVersionCode() > BuildConfig.VERSION_CODE) {
                            //TODO:提醒是否需要更新
//                            DialogModel model = new DialogModel("版本更新",version.getUpdateMessage());
//                            DialogUtils.showConfirmDialog(model, new DialogUtils.DialogClickListener() {
//                                @Override
//                                public void onConfirm() {
//                                    RxBus.getDefault().post(version);
//                                }
//
//                                @Override
//                                public void onCancel() {
//
//                                }
//                            });
                            RxBus.getDefault().post(version);
                        } else {
                            Log.d("update", "onNext: 无需更新");
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                //e.printStackTrace();
                            }
                            JumpMain(context);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException ex) {
                            //e.printStackTrace();
                        }
                        JumpMain(context);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
        return true;
    }

    public static void JumpMain(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        //当前页不允许返回
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }
}
